package com.me.util;

import java.io.*;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class FileUtils {

	/**
	 * 转换文件大小格式
	 * @param b
	 * @return
	 */
	public static String formatB(long b) {

		if (b >= 1073741824L) { // GB等级

			return formatDoubleNum(b / 1024 / 1024 / 1024D) + "GB";

		} else if (b >= 1048576) { // MB级别

			return formatDoubleNum(b / 1024 / 1024D) + "MB";

		} else if (b >= 1024) { // KB级别

			return formatDoubleNum(b / 1024D) + "KB";

		} else {

			return (int) b + "Byte";

		}

	}

	/**
	 * 保留两位小数 向下取
	 * @param num
	 * @return
	 */
	public static String formatDoubleNum(double num) {

		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance();
		df.setGroupingUsed(false);
		df.setMaximumFractionDigits(2);
		df.setRoundingMode(RoundingMode.HALF_UP);
		return df.format(num);

	}

	/**
	 * 获取文件名称，去掉扩展名
	 * @param name
	 * @return
	 */
	public static String getFileLastName(String name) {
		if (name.contains(".")) {
			return name.substring(name.lastIndexOf(".") + 1, name.length());
		}
		return null;
	}
	
	/**
	 * 获取文件扩展名
	 * @param name
	 * @return
	 */
	public static String getFileFirstName(String name) {
		if (name.contains(".")) {
			return name.substring(0,name.lastIndexOf("."));
		}
		return null;
	}
	
	/**
	 * 文件copy
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void copyFile(InputStream is,OutputStream os) throws Exception{
		int read=0;
		byte b[] = new byte[1024];
		try{
			while((read=is.read(b))>0){
				os.write(b,0,read);
			}
			os.flush();
		}catch (Exception e){
			try{
				os.close();
			}catch (Exception e1){}
			try{
				is.close();
			}catch (Exception e1){}
		}
	}
	
	public static byte[] readFileToByteArray(File file) throws Exception{
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try{
			fis = new FileInputStream(file);
			bos = new ByteArrayOutputStream();
			int read;
			byte b[] = new byte[1024];
			while((read=fis.read(b))>-1){
				bos.write(b,0,read);
			}
		}catch (Exception e){
			try{
				fis.close();
			}catch (Exception e1){}
		}
		return bos.toByteArray();
	}

	public static void saveObject(Object obj,String path){
		FileOutputStream fos = null;
		ObjectOutputStream oos =null;
		try {
			fos = new FileOutputStream(path);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
			fos.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try{
				oos.close();
			}catch (Exception e){}
			try{
				fos.close();
			}catch (Exception e){}
		}
	}
	public static Object readObject(String path){
		FileInputStream fis = null;
		ObjectInputStream ois =null;
		try {
			fis = new FileInputStream(path);
			ois = new ObjectInputStream(fis);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try{
				ois.close();
			}catch (Exception e){}
			try{
				fis.close();
			}catch (Exception e){}
		}
	}

}
